<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat, toYuan, copyToCliboard, getNowDay } from '@/hooks/util'
import * as accountApi from '@/api/account'
import * as financialCenterApi from '@/api/financialCenter'

import { message } from 'ant-design-vue'
import EditRemark from './components/EditRemark.vue'

const route = useRoute()

const editRemarkRef = ref()
const activeKey = ref<string>('1')

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  orderNumber?: string
  fansId?: string
  robotId?: string
  changeType?: string
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '订单信息',
    key: 'orderId',
    width: 300,
  },
  {
    title: '粉丝信息',
    key: 'fansId',
    width: 300,
  },
  {
    title: '变动信息',
    key: 'changeType',
    width: 300,
  },
  {
    title: '变动金额',
    key: 'changeBalance',
    width: 300,
  },
  {
    title: '变动时间',
    key: 'updateTime',
    width: 400,
    fixed: 'right',
  },
  // {
  //   title: '变动备注',
  //   key: 'changeRemark',
  //   width: 300,
  //   fixed: 'right',
  // },
  // {
  //   title: '操作',
  //   key: 'action',
  //   width: 90,
  //   fixed: 'right',
  // },
]

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize

  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let {
      state,
      data,
      message: msg,
    } = await financialCenterApi.getBalanceRecordList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

// 拉取机器人列表
let okRobat = ref<string>()
import type { SelectProps } from 'ant-design-vue'
const robatList = ref<SelectProps['options']>([])
interface OptionList {
  label: string
  value: string
}
let optionList = ref<Array<OptionList>>([])
const getRobatList = async () => {
  const params = {
    currentPage: 1,
    pageSize: 100,
  }
  try {
    let { state, data, message: msg } = await accountApi.getList(params)
    if (state === 200) {
      robatList.value = data.list
      optionList.value = data.list.map((item: any) => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })

      if (data.list.length == 0) {
        message.error('无平台账号，请先添加平台账号')
      } else if (data.list.length > 0) {
        selectRobat(data.list[0].id)
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const selectRobat = (selectValue: unknown) => {
  okRobat.value = selectValue as string
  searchParams.value.robotId = okRobat.value
  getList()
}

// 	变动类型
const typeList = ref<SelectProps['options']>([
  {
    label: '转账充值',
    value: '1',
  },
  {
    label: '订单退款',
    value: '2',
  },
  {
    label: '后台操作加款',
    value: '3',
  },
  {
    label: '订单扣款',
    value: '11',
  },
  {
    label: '后台操作扣款',
    value: '12',
  },
  {
    label: '余额扣除',
    value: '13',
  },
])

const compileType = (type: number | string) =>
  typeList.value?.find(item => item.value == type)?.label

onMounted(() => getRobatList())

// 查询
const formRef = ref()
interface FormState {
  changeType?: string
  orderNumber?: string
  fansId?: string
}
const formState = reactive<FormState>({})
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.orderNumber = formState.orderNumber || ''
    searchParams.value.fansId = formState.fansId || ''
    searchParams.value.changeType = formState.changeType || ''
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.resetFields()
  Reflect.deleteProperty(searchParams.value, 'orderNumber')
  Reflect.deleteProperty(searchParams.value, 'fansId')
  Reflect.deleteProperty(searchParams.value, 'changeType')

  getList()
}

// 备注
const editRemark = (id: string) => {
  editRemarkRef.value.showModal(id)
}

// select搜索
const filterOption = (input: string, option: any) => {
  return option.label.indexOf(input) >= 0
}

// 导出表格
let exportExcelLoading = ref<boolean>(false)
const exportExcel = async () => {
  try {
    exportExcelLoading.value = true
    let {
      state,
      data,
      message: msg,
    } = await financialCenterApi.balanceRecordExcelOut(searchParams.value)
    // console.log('data=', data)
    let blob = new Blob([data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    let file = new File([blob], `微信-财务日志-${getNowDay()}.xlsx`, {
      lastModified: new Date() as any,
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    // console.log('file=', file)
    const a = document.createElement('a')
    a.style.display = 'none'
    document.body.appendChild(a)
    const url = URL.createObjectURL(file)
    a.href = url
    a.download = file.name
    a.click()
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  exportExcelLoading.value = false
}
</script>

<template>
  <page-container :title="route.meta.title">
    <a-alert
      message="重要提醒"
      description="当前显示的为第一个账号的数据，如需加载指定账号数据请在右上角输入框进行选择微信账号/选择闲鱼账号操作！"
      type="warning"
      show-icon
      style="margin-bottom: 10px"
    />

    <a-card style="overflow-x: scroll">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="闲鱼">
          <div>请前往闲鱼平台功能 - 订单管理，或闲鱼app查看</div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="微信">
          <div style="margin: 5px 0; text-align: right">
            <span>选择微信账号：</span>
            <a-select
              v-model:value="okRobat"
              @change="selectRobat"
              placeholder="请选择"
              style="width: 200px; text-align: left"
              show-search
              :options="optionList"
              :filter-option="filterOption"
            >
              <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </div>

          <div class="searchBox">
            <a-form ref="formRef" layout="inline" :model="formState">
              <a-form-item label="订单编号" name="orderNumber">
                <a-input
                  v-model:value="formState.orderNumber"
                  placeholder="订单编号"
                  style="width: 200px"
                />
              </a-form-item>

              <a-form-item label="粉丝ID" name="fansId">
                <a-input
                  v-model:value="formState.fansId"
                  placeholder="粉丝ID"
                  style="width: 200px"
                />
              </a-form-item>

              <a-form-item label="变动类型" name="changeType">
                <a-select
                  v-model:value="formState.changeType"
                  placeholder="请选择"
                  style="width: 200px"
                  allowClear
                >
                  <a-select-option
                    v-for="(item, index) in typeList"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
            <a-button type="primary" @click="search">搜索</a-button>
            <a-button @click="reset">重置</a-button>
            <a-button :loading="exportExcelLoading"  :disabled="true" @click="exportExcel">
              <template #icon>
                <VerticalAlignBottomOutlined />
              </template>
              导出近七天
            </a-button>
          </div>

          <a-alert
            description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格"
            type="info"
            banner
            style="margin-bottom: 10px; padding: 10px"
          />

          <a-table
            style="overflow-x: scroll"
            :columns="columns"
            :data-source="dataSource"
            :pagination="pagination"
            :loading="loading"
            @change="changePage"
            rowKey="id"
            size="small"
            :scroll="{ x: 100 }"
          >
            <template #emptyText>
              <a-empty description="暂无数据" />
            </template>

            <template #headerCell="{ column }">
              <template v-if="column.key === 'id'">
                <span>id</span>
              </template>
            </template>

            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'orderId'">
                <a-descriptions bordered size="small" :column="1">
                  <a-descriptions-item label="id">{{ record.id }}</a-descriptions-item>
                  <a-descriptions-item label="订单编号">
                    {{ record.orderNumber }}
                    <a @click="copyToCliboard(record.orderNumber)">
                      <CopyOutlined />
                    </a>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-if="column.key === 'fansId'">
                <a-descriptions bordered size="small" :column="1">
                  <a-descriptions-item label="昵称">
                    <a-tooltip placement="top" v-if="!record.isRemarkShow">
                      <template #title>
                        <span>{{ record.wechatFansVO?.nickName }}</span>
                      </template>
                      <span class="hiddenText">{{ record.wechatFansVO?.nickName }}</span>
                    </a-tooltip>
                  </a-descriptions-item>
                  <a-descriptions-item label="粉丝ID">
                    {{ record.fansId }}
                    <a @click="copyToCliboard(record.fansId)">
                      <CopyOutlined />
                    </a>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'changeType'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
                  <a-descriptions-item label="变动金额">
                    ￥{{ toYuan(record.changeBalance) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="变动类型">
                    <a-tag
                      color="red"
                      v-if="
                        record.changeType == '2' ||
                        record.changeType == '11' ||
                        record.changeType == '12'
                      "
                    >
                      {{ compileType(record.changeType) }}
                    </a-tag>
                    <a-tag color="blue" v-else>{{ compileType(record.changeType) }}</a-tag>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'changeBalance'">
                <a-descriptions bordered size="small" :column="1">
                  <a-descriptions-item label="变动前">
                    ￥{{ toYuan(record.beforeBalance) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="变动后">
                    ￥{{ toYuan(record.afterBalance) }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'updateTime'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
                  <a-descriptions-item label="变动时间">
                    {{ timeFormat(record.updateTime) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="变动备注">
                    <a-tooltip placement="top" v-if="!record.isRemarkShow">
                      <template #title>
                        <span>{{ record.changeRemark }}</span>
                      </template>
                      <span class="hiddenText">{{ record.changeRemark }}</span>
                    </a-tooltip>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'action'">
                <div style="width: 100px; margin: 0; padding: 0">
                  <a @click="editRemark(record.id)">修改备注</a>
                </div>
              </template>
            </template>
          </a-table>

          <EditRemark ref="editRemarkRef" @refresh="getList"></EditRemark>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </page-container>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}
</style>
